package com.app.jzgdirector.common.retrofit;


import android.os.Handler;
import com.app.jzgdirector.MainApplication;
import com.app.jzgdirector.R;
import com.app.jzgdirector.common.constant.AppConstant;
import com.app.jzgdirector.common.util.ToastUtils;
import com.common.baselibrary.utils.NetworkUtil;
import java.util.concurrent.TimeUnit;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * 基本数据请求工具类
 * Created by：hcs on 2016/10/17 15:15
 * e_mail：aaron1539@163.com
 */
public class RetrofitUtils {
    public static final String BASE_URL = ApiService.baseUrl;
    private static final int DEFAULT_TIMEOUT = 10;
    private Retrofit retrofit;
    private ApiService service;
    private static RetrofitUtils INSTANCE;
		private Handler mHandler;

    private RetrofitUtils(){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
				mHandler=new Handler();
        builder.addInterceptor(chain -> {
						boolean connected = NetworkUtil.isAvailable(MainApplication.getInstance());
						if (!connected){
								mHandler.post(() -> {
										new ToastUtils(MainApplication.getInstance()).showSingleToast(R.string.no_internet);
								});
						}
						return chain.proceed(chain.request());
				}).addInterceptor(chain -> {
						Request oldRequest = chain.request();
						// 添加新的参数
						HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
							.newBuilder()
							.scheme(oldRequest.url().scheme())
							.host(oldRequest.url().host())
							.addQueryParameter("appkey", AppConstant.appkey);
						// 新的请求
						Request newRequest = oldRequest.newBuilder()
							.method(oldRequest.method(), oldRequest.body())
							.url(authorizedUrlBuilder.build())
							.build();
						return chain.proceed(newRequest);
				}).retryOnConnectionFailure(true);
        retrofit = new Retrofit.Builder()
                .client(builder.build())
								.addConverterFactory(StringConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BASE_URL)
                .build();
        service = retrofit.create(ApiService.class);
    }

    public static RetrofitUtils getInstance(){
				if(INSTANCE == null){
            synchronized (RetrofitUtils.class){
                if(INSTANCE == null){
                    INSTANCE = new RetrofitUtils();
                }
            }
        }
        return INSTANCE;
    }

    public Retrofit getRetrofit() {
        return retrofit;
    }

    public ApiService getService() {
        return service;
    }
}
